"use client";
import React, { useEffect, useMemo, useRef, useState } from "react";
import style from "./index.module.scss";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import "./index.css";
import { Button, Form, Input, Popover, message } from "antd";
import UploadImg from "@/components/UploadImg";
import {
  getPostById,
  getType,
  getUserById,
  publishPostByUser,
  updatePost,
  upload,
} from "@/api";
import { formats, modules } from "@/configs/constant";
import { useForm } from "antd/es/form/Form";
import { useRouter, useSearchParams } from "next/navigation";
import { useStore, useStoreType } from "@/zustand/store";
import { headers } from "next/headers";
interface IPublishPost {}

export const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const PublishPost: React.FC<IPublishPost> = () => {
  const [postContent, setPostContent] = useState("");
  const [postType, setPostType] = useState([]);
  const [form] = useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [imgUrl, setImgUrl] = useState("");
  const [slectType, setSlectType] = useState("");
  const [userName, setUserName] = useState("");
  const quillRef = useRef<ReactQuill>(null);
  const vedioInput = useRef<HTMLInputElement>(null);
  const userId = useStore((state: useStoreType) => state.userId);
  const searchParam = useSearchParams();
  const handleChangeValue = (value: string) => {
    setPostContent(value);
  };
  const router = useRouter();
  const onFinish = async (values: any) => {
    let result;
    if (searchParam.get("postId")) {
      const res = await updatePost({
        id: parseInt(searchParam.get("postId") || "0"),
        postAuthorName: userName,
        postContent,
        postStatus: 0,
        postType: slectType,
        postSummary: values.postSummary,
        postTitle: values.postTitle,
        postPhoto: imgUrl,
      });
      result = res;
    } else {
      const res = await publishPostByUser({
        postAuthorName: userName,
        postContent,
        postStatus: 0,
        postType: slectType,
        postSummary: values.postSummary,
        postTitle: values.postTitle,
        postPhoto: imgUrl,
      });
      result = res;
    }
    if (result.data.code === 200) {
      form.resetFields();
      setPostContent("");
      setImgUrl("");
      setSlectType("");
      message.success(searchParam.get("postId") ? "编辑成功" : "发布成功");
      router.push("/PersonalPost");
    } else {
      message.error(result.data.data.msg);
    }
  };
  const getPostType = async () => {
    const res = await getType({
      differ: "post",
      pageNum: 1,
      pageSize: 100,
    });
    setPostType(res.data.data.records);
  };
  const initPostById = async () => {
    const res = await getPostById({ id: searchParam.get("postId") });
    const resUser = await getUserById({ id: userId });
    const data = res.data.data.post;
    setUserName(resUser.data.data.userName);
    setPostContent(data.postContent);
    setSlectType(data.postType);
    setImgUrl(data.postPhoto);
    form.setFieldsValue(data);
  };
  const module = {
    toolbar: [
      [{ container: "#quill-edit-toolbar" }],
      [
        {
          handlers: {
            video: () => {
              console.log(vedioInput.current);
              vedioInput.current?.click();
            },
          },
        },
      ],
      [{ header: [1, 2, 3, false] }],
      ["bold", "italic", "underline", "strike"],
      ["blockquote", "code-block"],
      [{ list: "ordered" }, { list: "bullet" }],
      ["link", "image", "video"],
      ["clean"],
    ],
  };
  useEffect(() => {
    getPostType();
    if (searchParam.get("postId")) {
      initPostById();
    }
  }, []);

  async function uploadImg(e: React.ChangeEvent<HTMLInputElement>) {
    setLoading(true);
    if (e.target.files) {
      const files = e.target.files[0];
      var formData = new FormData();
      formData.append("files", files);
      const response = await upload(formData);
      if (response.data.code === 200) {
        setImgUrl(response.data.data[0]);
        setLoading(false);
        message.success(response.data.msg);
      } else {
        message.error(response.data.msg);
      }
    }
  }
  const handleTypeItem = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    setSlectType(e.currentTarget.innerHTML);
  };
  const typeList = () => {
    return (
      <div className={style["listContainer"]}>
        {postType.map((item: any, index: number) => (
          <div className={style["item"]} onClick={handleTypeItem} key={index}>
            {item.typeName}
          </div>
        ))}
      </div>
    );
  };
  const handleClick = (e: any) => {
    console.log(e);
  };
  return (
    <div className={style["bg"]}>
      <div className={style["body"]}>
        <div className={style["content"]}>
          <ReactQuill
            placeholder="请输入你想编辑的内容"
            theme="snow"
            value={postContent}
            onChange={handleChangeValue}
            formats={formats}
            modules={modules}
          />
          <div className={style["editorFooter"]}></div>
        </div>
        <div className={style["postForm"]}>
          <Form
            {...layout}
            name="nest-messages"
            onFinish={onFinish}
            style={{ maxWidth: 600 }}
            form={form}
          >
            <Form.Item name={"postPhoto"} label="编程讨论封面" rules={[]}>
              <UploadImg
                onChange={uploadImg}
                isLoading={loading}
                imgUrl={imgUrl}
              />
            </Form.Item>
            <Form.Item name={"postTitle"} label="编程讨论标题" rules={[]}>
              <Input placeholder="请输入文章标题" />
            </Form.Item>
            <Form.Item name={"postSummary"} label="编程讨论摘要">
              <Input placeholder="请输入文章摘要"></Input>
            </Form.Item>
            <Form.Item name={"postType"} label="编程讨论分类">
              <Popover placement="right" content={typeList()}>
                <div className={style["postTypeBtn"]}>
                  {slectType ? slectType : "选择分类"}
                </div>
              </Popover>
            </Form.Item>
            <Form.Item label={null} wrapperCol={{ span: 8, offset: 14 }}>
              <Button type="primary" htmlType="submit" style={{ width: 130 }}>
                {searchParam.get("postId") ? "编辑编程讨论" : "发布编程讨论"}
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};
export default PublishPost;
